<?php

namespace app\api\controller;

use addons\epay\library\Service;
use app\common\controller\Api;
use Yansongda\Pay\Exceptions\Exception;

class Order extends Api
{
    protected $noNeedLogin = ['delOrder','getorderInfo','createOrder'];
    protected  $noNeedRight=["*"];
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Order();

    }
    public function createOrder(){
        $storeModel = new \app\admin\model\Store();
        $store_id = $storeModel->where('status', 2)->value('id');
        $name = 'epay';
        $info = get_addon_info($name);
        $config = get_addon_fullconfig($name);
        if (!$info) {
            $this->error(__('Addon not exists'));
        }
        $newConfig = $config[$store_id];
        if(empty($newConfig)){
            $this->error("商户信息错误");
        }
        $this->request->filter('trim');
        $out_trade_no = $this->ordersnum();
        $title = '普通收款';
        $admin_id = $this->request->request("admin_id");

        $amount = $this->request->request('amount');
        $type = $this->request->request('type', $this->request->request('paytype'));
        $method = $this->request->request('method', 'wap');
        $openid = $this->request->request('openid', '');
        $auth_code = $this->request->request('auth_code', '');
        $notifyurl = $this->request->request('notifyurl', '');
        $returnurl = $this->request->request('returnurl', '');

        if (!$amount || $amount < 0) {
            $this->error("支付金额必须大于0");
        }

        if (!$type || !in_array($type, ['alipay', 'wechat'])) {
            $this->error("支付类型错误");
        }
        $this->model->startTrans();
        try {
            $orderdata = [
                'store_id' => $store_id,
                'order_sn' => $out_trade_no,
                'price' => $amount,
                'pay_type' => $type,
                'user_id' => $this->auth->id,
                'create_time' => time(),
                'admin_id' => $admin_id,
            ];
            $this->model->save($orderdata);
            $params = [
                'type'         => $type,
                'orderid'=>$out_trade_no,
                'out_trade_no' => $out_trade_no,
                'title'        => $title,
                'amount'       => $amount,
                'method'       => $method,
                'openid'       => $openid,
                'auth_code'    => $auth_code,
                'notifyurl'    => $notifyurl,
                'returnurl'    => $returnurl,
                'addonConfig'=>$newConfig,
                'store_id'  =>  $store_id
            ];
//            $res = Service::submitOrder($params);
//            $params = [
//                'amount'=>"99.9",
//                'orderid'=>$out_trade_no,
//                'type'=>"alipay",
//                'title'=>"订单标题",
//                'notifyurl'=>$notifyurl,
//                'returnurl'=>$returnurl,
//                'method'=>"wap",
//                'openid'=>"用户的OpenID",
//                'auth_code'=>"验证码",
//                'addonConfig'=>$newConfig,
//                'store_id'  =>  $store_id
//            ];
            $res = \addons\epay\library\Service::submitOrder($params);
            if($type=='alipay'){
                $pay['content'] = $res->getContent();
            }else{
                $pay = $res;
            }
            $this->model->commit();

            $pay['order_sn'] = $out_trade_no;
            $this->success("创建成功",$pay);
        }catch (Exception $e){
            $this->model->rollback();
            $this->error($e->getMessage());
        }

    }

    public function getorderInfo(){
        $order_id = $this->request->param('out_trade_no');
        $ordermodel = new  \app\admin\model\Order();
        $order = $ordermodel->where('order_sn',$order_id)->find();
        $this->success($order);
    }
    /*
 * 生成订单号
 * */
    protected function ordersnum()
    {
        $code = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T');
        $char = $code[intval(date('Y')) - 2019] . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));
        $res = $this->model->where("order_sn='$char'")->find();
        if ($res) {
            $this->ordersnum();
        }
        return $char;
    }

    public function delOrder(){
        $this->model->whereBetween('create_time',[time()-15*60,time()])->where(['pay_status'=>1])->delete();
        $this->success("删除成功");
    }
}